<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="工单ID" prop="ticket_id">
        <el-input
          v-model="queryParams.ticket_id"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>

      <!-- <el-form-item label="来源渠道" prop="source">
        <el-select
          v-model="queryParams.source"
          placeholder="请选择来源渠道"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="当前状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择当前状态"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select
          v-model="queryParams.priority"
          placeholder="请选择优先级"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 运维特有字段 -->
      <el-form-item label="故障级别" prop="severity">
        <el-select
          v-model="queryParams.severity"
          placeholder="请选择故障级别"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in severityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主要工程师" prop="primary_engineer">
        <el-input
          v-model="queryParams.primary_engineer"
          placeholder="请输入主要工程师"
          clearable
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="create_time">
        <el-date-picker
          v-model="queryParams.create_time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增工单
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
        <!-- <el-button link type="primary" @click="okdialog"> 问卷调查 </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="paginatedList"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column
        label="工单ID"
        align="center"
        prop="ticket_id"
        width="100"
      />

      <el-table-column
        label="来源渠道"
        align="center"
        prop="source"
        width="120"
      >
        <template #default="{ row }">
          {{ sourceMap[row.source] || row.source }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        :formatter="dateFormatter"
        width="160"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="update_time"
        :formatter="dateFormatter"
        width="160"
      />
      <el-table-column
        label="当前状态"
        align="center"
        prop="status"
        width="120"
      >
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]">
            {{ statusMap[row.status] || row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80">
        <template #default="{ row }">
          <el-tag :type="priorityTagType[row.priority]">
            {{ row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 运维特有字段 -->
      <el-table-column
        label="设备ID"
        align="center"
        prop="device_id"
        width="120"
      />
      <el-table-column
        label="设备序列号"
        align="center"
        prop="serial_number"
        width="150"
      />
      <el-table-column
        label="故障级别"
        align="center"
        prop="severity"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="severityTagType[row.severity]">
            {{ severityMap[row.severity] || row.severity }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="故障代码"
        align="center"
        prop="error_code"
        width="120"
      />
      <el-table-column
        label="故障描述"
        align="left"
        prop="description"
        min-width="200"
      />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.ticket_id)"
          >
            编辑
          </el-button>
          <el-button link type="info" @click="openDetail(scope.row.ticket_id)">
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.ticket_id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="filteredTotal"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="form-grid"
    >
      <el-form-item
        label="工单ID"
        prop="ticket_id"
        v-if="formType === 'update'"
      >
        <el-input v-model="formData.ticket_id" disabled />
      </el-form-item>

      <!-- <el-form-item label="来源渠道" prop="source">
        <el-select v-model="formData.source" placeholder="请选择来源渠道">
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="当前状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择当前状态">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="formData.priority" placeholder="请选择优先级">
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 运维特有字段 -->
      <el-form-item label="设备ID" prop="device_id">
        <el-input v-model="formData.device_id" placeholder="请输入设备ID" />
      </el-form-item>
      <el-form-item label="设备序列号" prop="serial_number">
        <el-input
          v-model="formData.serial_number"
          placeholder="请输入设备序列号"
        />
      </el-form-item>
      <el-form-item label="产品型号" prop="product_model">
        <el-input
          v-model="formData.product_model"
          placeholder="请输入产品型号"
        />
      </el-form-item>
      <el-form-item label="故障代码" prop="error_code">
        <el-input v-model="formData.error_code" placeholder="请输入故障代码" />
      </el-form-item>
      <el-form-item label="故障级别" prop="severity">
        <el-select v-model="formData.severity" placeholder="请选择故障级别">
          <el-option
            v-for="item in severityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障发生时间" prop="failure_time">
        <el-date-picker
          v-model="formData.failure_time"
          type="datetime"
          placeholder="选择故障发生时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="故障描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入故障描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 详情弹窗 -->
  <el-dialog title="工单详情" v-model="detailVisible" width="800px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="工单ID">{{
        detailData.ticket_id
      }}</el-descriptions-item>

      <el-descriptions-item label="来源渠道">
        {{ sourceMap[detailData.source] || detailData.source }}
      </el-descriptions-item>

      <el-descriptions-item label="当前状态">
        <el-tag :type="statusTagType[detailData.status]">
          {{ statusMap[detailData.status] || detailData.status }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="优先级">
        <el-tag :type="priorityTagType[detailData.priority]">
          {{ detailData.priority }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="设备ID">{{
        detailData.device_id
      }}</el-descriptions-item>
      <el-descriptions-item label="设备序列号">{{
        detailData.serial_number
      }}</el-descriptions-item>
      <el-descriptions-item label="产品型号">{{
        detailData.product_model
      }}</el-descriptions-item>
      <el-descriptions-item label="故障代码">{{
        detailData.error_code
      }}</el-descriptions-item>
      <el-descriptions-item label="故障级别">
        <el-tag :type="severityTagType[detailData.severity]">
          {{ severityMap[detailData.severity] || detailData.severity }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="故障发生时间">{{
        detailData.failure_time
      }}</el-descriptions-item>
      <el-descriptions-item label="故障描述" :span="2">
        {{ detailData.description }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button type="primary" @click="detailVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from "@/utils/formatTime";
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
defineOptions({ name: "OperationTicket" }); // 修改组件名
import { useUserStoreWithOut } from "@/store/modules/user";
const userStore = useUserStoreWithOut(); // 用户信息缓存
const message = useMessage();
const { t } = useI18n();

// 列表相关状态
const loading = ref(true);
const ticketList = ref([]);
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  ticket_id: undefined,
  ticket_type: undefined,
  source: undefined,
  status: undefined,
  priority: undefined,
  severity: undefined, // 新增故障级别查询
  primary_engineer: undefined, // 新增主要工程师查询
  create_time: [],
});
const queryFormRef = ref();
// const exportLoading = ref(false); 导出加载
// //----- 问卷调查相关
// // 存储所有调查数据
// const surveyData = ref([]);
// const STORAGE_KEY = "SURVEY_RESULTS";

// const dialog = ref(false);
// const okdialog = () => {
//   dialog.value = true;
// };
// // 表单数据结构
// const form = ref({
//   satisfaction: 3, // 默认3星
//   reuse: "yes",
//   suggestions: [],
//   comments: "",
// });

// // 提交调查
// const submitSurvey = () => {
//   // 添加时间戳
//   const result = {
//     ...form.value,
//     timestamp: new Date().toLocaleString(),
//   };

//   // 添加到数据数组
//   surveyData.value.push(result);

//   // 保存到LocalStorage
//   localStorage.setItem(STORAGE_KEY, JSON.stringify(surveyData.value));

//   // 重置表单
//   form.value = {
//     satisfaction: 3,
//     reuse: "yes",
//     suggestions: [],
//     comments: "",
//   };

//   ElMessage.success("提交成功！数据已保存到本地");
// };

// -----
// 弹窗相关状态
const dialogVisible = ref(false);
const detailVisible = ref(false);
const dialogTitle = ref("");
const formType = ref(""); // 'create' | 'update'
const formData = ref({
  ticket_id: undefined,
  ticket_type: "运维",
  source: "系统上报",
  create_time: undefined,
  update_time: undefined,
  status: "待分配",
  priority: "P2",
  device_id: "",
  serial_number: "",
  product_model: "",
  error_code: "",
  severity: "一般",
  primary_engineer: "",
  failure_time: "",
  description: "",
});
const detailData = ref({});
const formRef = ref();
const formRules = reactive({
  ticket_type: [
    { required: true, message: "工单类型不能为空", trigger: "change" },
  ],
  source: [{ required: true, message: "来源渠道不能为空", trigger: "change" }],
  status: [{ required: true, message: "当前状态不能为空", trigger: "change" }],
  priority: [{ required: true, message: "优先级不能为空", trigger: "change" }],
  severity: [
    { required: true, message: "故障级别不能为空", trigger: "change" },
  ],
  primary_engineer: [
    { required: true, message: "主要工程师不能为空", trigger: "blur" },
  ],
  description: [
    { required: true, message: "故障描述不能为空", trigger: "blur" },
  ],
});

// 下拉选项
const ticketTypeOptions = [
  { value: "运维", label: "运维" },
  { value: "售后", label: "售后" },
];

const sourceOptions = [
  { value: "系统上报", label: "系统上报" },
  { value: "系统上报", label: "系统上报" },
  { value: "系统上报", label: "系统上报" },
  { value: "系统上报", label: "系统上报" },
  { value: "系统上报", label: "系统上报" },
];

const statusOptions = [
  { value: "待分配", label: "待分配" },
  { value: "已分配", label: "已分配" },
  { value: "处理中", label: "处理中" },
  { value: "待确认", label: "待确认" },
  { value: "已完成", label: "已完成" },
  { value: "已关闭", label: "已关闭" },
  { value: "已取消", label: "已取消" },
];

const priorityOptions = [
  { value: "P0", label: "P0 (最高)" },
  { value: "P1", label: "P1 (高)" },
  { value: "P2", label: "P2 (中)" },
  { value: "P3", label: "P3 (低)" },
  { value: "P4", label: "P4 (最低)" },
];

// 新增故障级别选项
const severityOptions = [
  { value: "致命", label: "致命" },
  { value: "严重", label: "严重" },
  { value: "一般", label: "一般" },
  { value: "轻微", label: "轻微" },
];

// 映射关系
const sourceMap = {
  电话: "电话",
  邮件: "邮件",
  系统上报: "系统上报",
  APP: "APP",
  微信: "微信",
};

const statusMap = {
  待分配: "待分配",
  已分配: "已分配",
  处理中: "处理中",
  待确认: "待确认",
  已完成: "已完成",
  已关闭: "已关闭",
  已取消: "已取消",
};

// 新增故障级别映射
const severityMap = {
  致命: "致命",
  严重: "严重",
  一般: "一般",
  轻微: "轻微",
};

// 标签类型映射
const statusTagType = {
  待分配: "info",
  已分配: "",
  处理中: "warning",
  待确认: "primary",
  已完成: "success",
  已关闭: "danger",
  已取消: "danger",
};

const priorityTagType = {
  P0: "danger",
  P1: "warning",
  P2: "",
  P3: "primary",
  P4: "success",
};

// 新增故障级别标签类型
const severityTagType = {
  致命: "danger",
  严重: "warning",
  一般: "",
  轻微: "success",
};

// 初始化本地数据
const initLocalData = () => {
  if (userStore.user.nickname == "超级管理员") {
    ticketList.value = [
      {
        ticket_id: "OPS20230710001", // OPS前缀表示运维工单
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 09:25:30",
        update_time: "2023-07-10 14:30:45",
        status: "处理中",
        priority: "P1",
        device_id: "SRV-1001",
        serial_number: "SN-OP20230710001",
        product_model: "Server Pro X",
        error_code: "ERR-5001",
        severity: "严重",
        failure_time: "2023-07-10 09:00:00",
        description: "服务器CPU使用率持续超过90%，需要优化",
      },
      {
        ticket_id: "OPS20230710002",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 10:15:22",
        update_time: "2023-07-10 10:30:18",
        status: "待分配",
        priority: "P2",
        device_id: "NET-2001",
        serial_number: "SN-OP20230710002",
        product_model: "Router Pro",
        error_code: "ERR-3002",
        severity: "一般",
        failure_time: "2023-07-10 09:45:00",
        description: "路由器端口流量异常，需检查配置",
      },
      {
        ticket_id: "OPS20230710003",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-09 14:30:45",
        update_time: "2023-07-10 09:15:30",
        status: "已完成",
        priority: "P3",
        device_id: "DB-3001",
        serial_number: "SN-OP20230710003",
        product_model: "Database Cluster",
        error_code: "ERR-1005",
        severity: "轻微",
        failure_time: "2023-07-09 13:20:00",
        description: "数据库连接数接近上限，需优化连接池",
      },
      {
        ticket_id: "OPS20230710004",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-08 16:45:12",
        update_time: "2023-07-10 11:20:33",
        status: "已关闭",
        priority: "P4",
        device_id: "STOR-4001",
        serial_number: "SN-OP20230710004",
        product_model: "Storage Array",
        error_code: "ERR-7003",
        severity: "致命",
        failure_time: "2023-07-08 16:30:00",
        description: "存储阵列RAID5磁盘故障，需立即更换",
      },
      {
        ticket_id: "OPS20230710005",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 13:05:18",
        update_time: "2023-07-10 13:05:18",
        status: "待确认",
        priority: "P2",
        device_id: "VM-5001",
        serial_number: "SN-OP20230710005",
        product_model: "Virtual Host",
        error_code: "ERR-6008",
        severity: "严重",
        failure_time: "2023-07-10 12:30:00",
        description: "虚拟机宿主机内存泄漏，需重启服务",
      },
    ];
  }
  if (userStore.user.nickname == "yunwei001") {
    ticketList.value = [
      {
        ticket_id: "OPS20230710001", // OPS前缀表示运维工单
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 09:25:30",
        update_time: "2023-07-10 14:30:45",
        status: "处理中",
        priority: "P1",
        device_id: "SRV-1001",
        serial_number: "SN-OP20230710001",
        product_model: "Server Pro X",
        error_code: "ERR-5001",
        severity: "严重",
        failure_time: "2023-07-10 09:00:00",
        description: "服务器CPU使用率持续超过90%，需要优化",
      },
      {
        ticket_id: "OPS20230710002",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 10:15:22",
        update_time: "2023-07-10 10:30:18",
        status: "待分配",
        priority: "P2",
        device_id: "NET-2001",
        serial_number: "SN-OP20230710002",
        product_model: "Router Pro",
        error_code: "ERR-3002",
        severity: "一般",
        failure_time: "2023-07-10 09:45:00",
        description: "路由器端口流量异常，需检查配置",
      },
      {
        ticket_id: "OPS20230710003",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-09 14:30:45",
        update_time: "2023-07-10 09:15:30",
        status: "已完成",
        priority: "P3",
        device_id: "DB-3001",
        serial_number: "SN-OP20230710003",
        product_model: "Database Cluster",
        error_code: "ERR-1005",
        severity: "轻微",
        failure_time: "2023-07-09 13:20:00",
        description: "数据库连接数接近上限，需优化连接池",
      },
    ];
  }
  if (userStore.user.nickname == "yunwei002") {
    ticketList.value = [
      {
        ticket_id: "OPS20230710004",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-08 16:45:12",
        update_time: "2023-07-10 11:20:33",
        status: "已关闭",
        priority: "P4",
        device_id: "STOR-4001",
        serial_number: "SN-OP20230710004",
        product_model: "Storage Array",
        error_code: "ERR-7003",
        severity: "致命",
        failure_time: "2023-07-08 16:30:00",
        description: "存储阵列RAID5磁盘故障，需立即更换",
      },
      {
        ticket_id: "OPS20230710005",
        ticket_type: "运维",
        source: "系统上报",
        create_time: "2023-07-10 13:05:18",
        update_time: "2023-07-10 13:05:18",
        status: "待确认",
        priority: "P2",
        device_id: "VM-5001",
        serial_number: "SN-OP20230710005",
        product_model: "Virtual Host",
        error_code: "ERR-6008",
        severity: "严重",
        failure_time: "2023-07-10 12:30:00",
        description: "虚拟机宿主机内存泄漏，需重启服务",
      },
    ];
  }
};

// 计算属性
const filteredList = computed(() => {
  let result = [...ticketList.value];

  // 工单ID筛选
  if (queryParams.ticket_id) {
    result = result.filter((item) =>
      item.ticket_id.includes(queryParams.ticket_id)
    );
  }

  // 工单类型筛选
  if (queryParams.ticket_type) {
    result = result.filter(
      (item) => item.ticket_type === queryParams.ticket_type
    );
  }

  // 来源渠道筛选
  if (queryParams.source) {
    result = result.filter((item) => item.source === queryParams.source);
  }

  // 状态筛选
  if (queryParams.status) {
    result = result.filter((item) => item.status === queryParams.status);
  }

  // 优先级筛选
  if (queryParams.priority) {
    result = result.filter((item) => item.priority === queryParams.priority);
  }

  // 故障级别筛选
  if (queryParams.severity) {
    result = result.filter((item) => item.severity === queryParams.severity);
  }

  // 主要工程师筛选
  if (queryParams.primary_engineer) {
    result = result.filter((item) =>
      item.primary_engineer.includes(queryParams.primary_engineer)
    );
  }

  // 创建时间筛选
  if (queryParams.create_time?.length === 2) {
    const [start, end] = queryParams.create_time;
    result = result.filter((item) => {
      const time = new Date(item.create_time).getTime();
      return (
        time >= new Date(start).getTime() && time <= new Date(end).getTime()
      );
    });
  }

  // 按创建时间降序排序
  // result.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));

  return result;
});

const paginatedList = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize;
  const end = start + queryParams.pageSize;
  return filteredList.value.slice(start, end);
});

const filteredTotal = computed(() => filteredList.value.length);

// 方法
const getList = () => {
  loading.value = false; // 本地数据无需加载
};

const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.create_time = [];
  handleQuery();
};

const openForm = (type: string, id?: string) => {
  formType.value = type;
  dialogTitle.value = type === "create" ? "新增工单" : "编辑工单";
  dialogVisible.value = true;

  // 重置表单
  formData.value = {
    ticket_id: undefined,
    ticket_type: "运维",
    source: "系统上报",
    create_time: new Date().toISOString().replace("T", " ").substring(0, 19),
    update_time: new Date().toISOString().replace("T", " ").substring(0, 19),
    status: "待分配",
    priority: "P2",
    device_id: "",
    serial_number: "",
    product_model: "",
    error_code: "",
    severity: "一般",
    primary_engineer: "",
    failure_time: "",
    description: "",
  };

  // 如果是编辑，填充数据
  if (id) {
    const ticket = ticketList.value.find((item) => item.ticket_id === id);
    if (ticket) {
      formData.value = { ...ticket };
    }
  }
};

const openDetail = (id: string) => {
  const ticket = ticketList.value.find((item) => item.ticket_id === id);
  if (ticket) {
    detailData.value = { ...ticket };
    detailVisible.value = true;
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    // 生成工单ID（如果是新增）
    if (formType.value === "create") {
      // 生成新的工单ID
      const maxId = Math.max(
        ...ticketList.value.map((item) =>
          parseInt(item.ticket_id.replace("OPS", ""))
        ),
        20230710000
      );
      formData.value.ticket_id = `OPS${maxId + 1}`;
      formData.value.create_time = new Date()
        .toISOString()
        .replace("T", " ")
        .substring(0, 19);

      // 添加到列表开头
      // ticketList.value.unshift({ ...formData.value });

      // 使用 push() 而不是 unshift()
      ticketList.value.push({ ...formData.value });
      // 自动滚动到最后一行
      setTimeout(() => {
        const tableWrapper = document.querySelector(".el-table__body-wrapper");
        if (tableWrapper) {
          tableWrapper.scrollTop = tableWrapper.scrollHeight;
        }
      }, 100);
      message.success("新增工单成功");
    } else {
      // 更新逻辑
      formData.value.update_time = new Date()
        .toISOString()
        .replace("T", " ")
        .substring(0, 19);
      const index = ticketList.value.findIndex(
        (item) => item.ticket_id === formData.value.ticket_id
      );
      if (index !== -1) {
        ticketList.value.splice(index, 1, formData.value);
      }
      message.success("更新工单成功");
    }

    dialogVisible.value = false;
    getList();
  } catch (e) {
    console.error("表单验证失败", e);
  }
};

const handleDelete = async (id: string) => {
  try {
    await message.delConfirm("确定删除该工单吗？");
    ticketList.value = ticketList.value.filter((item) => item.ticket_id !== id);
    message.success("删除工单成功");
    getList();
  } catch {}
};

// const handleExport = async () => {
//   try {
//     await message.exportConfirm();
//     exportLoading.value = true;
//     const data = JSON.stringify(filteredList.value, null, 2);
//     const blob = new Blob([data], { type: "application/json" });
//     const url = URL.createObjectURL(blob);
//     const link = document.createElement("a");
//     link.href = url;
//     link.download = "运维工单数据.json";
//     link.click();
//     URL.revokeObjectURL(url);
//     message.success("导出成功");
//   } finally {
//     exportLoading.value = false;
//   }
// };

// 初始化
onMounted(() => {
  initLocalData();
  getList();
});
</script>

<style scoped>
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>
